<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    <title>python装饰器 | Cucy的博客</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="python">
    <meta name="description" content="# coding:utf8&apos;&apos;&apos;&apos;&apos;&apos;&apos;&apos;&apos;------------------ 基本装饰器 ------------------ Start&apos;&apos;&apos;&apos;&apos;&apos; 一般写法&apos;&apos;&apos;&apos;&apos;&apos;$$$$$$$$$$$$$$$$$$$$$ Start $$$$$$$$$$$$$$$$$$$$$&apos;&apos;&apos;def hello():    return &apos;hello world!&apos;def makeitalic(func):">
<meta property="og:type" content="article">
<meta property="og:title" content="python装饰器">
<meta property="og:url" content="http://zhourudong.cn/2017/02/16/23-python装饰器/index.html">
<meta property="og:site_name" content="Cucy的博客">
<meta property="og:description" content="# coding:utf8&apos;&apos;&apos;&apos;&apos;&apos;&apos;&apos;&apos;------------------ 基本装饰器 ------------------ Start&apos;&apos;&apos;&apos;&apos;&apos; 一般写法&apos;&apos;&apos;&apos;&apos;&apos;$$$$$$$$$$$$$$$$$$$$$ Start $$$$$$$$$$$$$$$$$$$$$&apos;&apos;&apos;def hello():    return &apos;hello world!&apos;def makeitalic(func):">
<meta property="og:updated_time" content="2019-02-22T05:28:07.810Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="python装饰器">
<meta name="twitter:description" content="# coding:utf8&apos;&apos;&apos;&apos;&apos;&apos;&apos;&apos;&apos;------------------ 基本装饰器 ------------------ Start&apos;&apos;&apos;&apos;&apos;&apos; 一般写法&apos;&apos;&apos;&apos;&apos;&apos;$$$$$$$$$$$$$$$$$$$$$ Start $$$$$$$$$$$$$$$$$$$$$&apos;&apos;&apos;def hello():    return &apos;hello world!&apos;def makeitalic(func):">
    
        <link rel="alternate" type="application/atom+xml" title="Cucy的博客" href="/atom.xml">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="/css/style.css?v=1.6.13">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.png">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">cucy</h5>
          <a href="mailto:292016176@qq.com" title="292016176@qq.com" class="mail">292016176@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                Archives
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                Tags
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/cucy" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">python装饰器</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">python装饰器</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-02-16T09:26:05.000Z" itemprop="datePublished" class="page-time">
  2017-02-16
</time>


            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
<article id="post-23-python装饰器"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">python装饰器</h1>
        <div class="post-meta">
            <time class="post-time" title="2017-02-16 17:26:05" datetime="2017-02-16T09:26:05.000Z"  itemprop="datePublished">2017-02-16</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <figure class="highlight"><table><tr><td class="code"><pre><span class="line"># coding:utf8</span><br><span class="line"></span><br><span class="line">''''''</span><br><span class="line"></span><br><span class="line">'''------------------ 基本装饰器 ------------------ Start'''</span><br><span class="line">''' 一般写法'''</span><br><span class="line">'''$$$$$$$$$$$$$$$$$$$$$ Start $$$$$$$$$$$$$$$$$$$$$'''</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def hello():</span><br><span class="line">    return 'hello world!'</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def makeitalic(func):</span><br><span class="line">    def wrapped():</span><br><span class="line">        return '&lt;i&gt;' + func() + '&lt;/i&gt;'</span><br><span class="line"></span><br><span class="line">    return wrapped</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">hello = makeitalic(hello)  # 此步骤返回 wrapped 变量(wrapped函数,尚未执行)，</span><br><span class="line">print hello()  # 调用方法后wrapped函数是执行hello()函数,</span><br><span class="line">print hello.__name__  # 而 hello.__name__ 隐性变成wrapped</span><br><span class="line"></span><br><span class="line">&lt;!-- more --&gt;</span><br><span class="line">'''</span><br><span class="line">解析:</span><br><span class="line">    1、将hello函数当做参数传给makeitalic函数</span><br><span class="line">    2、makeitalic中wrapped函数给func()函数结果加上 &lt;i&gt; &lt;/i&gt;标签, 返回</span><br><span class="line">    3、makeitalic 最终返回的是 return '&lt;i&gt;' + func() + '&lt;/i&gt;'</span><br><span class="line">    4、makeitalic(func) 被称为装饰器,对hello进行装饰,返回一个变量(函数),赋值给hello</span><br><span class="line">'''</span><br><span class="line">'''$$$$$$$$$$$$$$$$$$$$$ End $$$$$$$$$$$$$$$$$$$$$'''</span><br><span class="line"></span><br><span class="line">''' 等价于(语法糖简略写法) '''</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def makeitalic(func):</span><br><span class="line">    def wrapped():</span><br><span class="line">        return '&lt;i&gt;' + func() + '&lt;/i&gt;'</span><br><span class="line"></span><br><span class="line">    return wrapped</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">@makeitalic</span><br><span class="line">def hello():</span><br><span class="line">    return 'hello world'</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">print hello()</span><br><span class="line"></span><br><span class="line">''' --------------------- 一般使用形式 --------------------- Start'''</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">@decorator</span><br><span class="line">def func():</span><br><span class="line">    pass</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 等价于下面的形式：</span><br><span class="line"></span><br><span class="line">def func():</span><br><span class="line">    pass</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">func = decorator(func)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 装饰器可以定义多个，离函数定义最近的装饰器先被调用</span><br><span class="line">@decorator_one</span><br><span class="line">@decorator_two</span><br><span class="line">def func():</span><br><span class="line">    pass</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">#  等价于</span><br><span class="line">def func():</span><br><span class="line">    pass</span><br><span class="line">func = decorator_one(decorator_two(func))</span><br><span class="line"></span><br><span class="line">''' --------------------- 一般使用形式 --------------------- End'''</span><br><span class="line"></span><br><span class="line">'''------------------ 基本装饰器 ------------------ End'''</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">'''------------------ 对带参数的函数进行装饰 ------------------ Start'''</span><br><span class="line">def makeitalic(func):</span><br><span class="line">    def wrapped(*args, **kwargs):</span><br><span class="line">        ret = func(*args, **kwargs)</span><br><span class="line">        return '&lt;i&gt;' + ret + '&lt;/i&gt;'</span><br><span class="line">    return wrapped</span><br><span class="line"></span><br><span class="line">@makeitalic</span><br><span class="line">def hello(name):</span><br><span class="line">    return "hello %s" % name</span><br><span class="line"></span><br><span class="line">@makeitalic</span><br><span class="line">def hello_2(name1, name2):</span><br><span class="line">    return 'hello %s, %s.' %(name1, name2)</span><br><span class="line"></span><br><span class="line">print hello('java')</span><br><span class="line"></span><br><span class="line">print hello_2('c++','python')</span><br><span class="line"></span><br><span class="line"># 返回值</span><br><span class="line">'''</span><br><span class="line">&lt;i&gt;hello java&lt;/i&gt;</span><br><span class="line">&lt;i&gt;hello c++, python.&lt;/i&gt;</span><br><span class="line">'''</span><br><span class="line"></span><br><span class="line">'''------------------ 装饰器的副作用 ------------------ Start'''</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def makeitalic(func):</span><br><span class="line">    def wrapped():</span><br><span class="line">        return "&lt;i&gt;" + func() + "&lt;/i&gt;"</span><br><span class="line">    return wrapped</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">@makeitalic</span><br><span class="line">def hello():</span><br><span class="line">    return 'hello world'</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">print hello.__name__</span><br><span class="line"></span><br><span class="line">'''</span><br><span class="line">函数 hello 被 makeitalic 装饰后，它的函数名称已经改变了：</span><br><span class="line">返回:</span><br><span class="line">wrapped</span><br><span class="line">'''</span><br><span class="line"># 修改</span><br><span class="line">from functools import wraps</span><br><span class="line"></span><br><span class="line">def makeitalic(func):</span><br><span class="line">    @wraps(func)       # 加上 wraps 装饰器</span><br><span class="line">    def wrapped():</span><br><span class="line">        return "&lt;i&gt;" + func() + "&lt;/i&gt;"</span><br><span class="line">    return wrapped</span><br><span class="line"></span><br><span class="line">@makeitalic</span><br><span class="line">def hello():</span><br><span class="line">    return 'hello world'</span><br><span class="line"></span><br><span class="line">print  hello.__name__</span><br><span class="line">'''</span><br><span class="line">'hello'</span><br><span class="line">'''</span><br><span class="line"></span><br><span class="line">'''------------------ 装饰器的副作用 ------------------ End'''</span><br></pre></td></tr></table></figure>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2019-02-22T05:28:07.810Z" itemprop="dateUpdated">2019-02-22 13:28:07</time>
</span><br>


        
        <a href="/2017/02/16/23-python装饰器/" target="_blank" rel="external">http://zhourudong.cn/2017/02/16/23-python装饰器/</a>
        
    </div>
    <footer>
        <a href="http://zhourudong.cn">
            <img src="/img/avatar.png" alt="cucy">
            cucy
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/python/">python</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://zhourudong.cn/2017/02/16/23-python装饰器/&title=《python装饰器》 — Cucy的博客&pic=http://zhourudong.cn/img/avatar.png" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://zhourudong.cn/2017/02/16/23-python装饰器/&title=《python装饰器》 — Cucy的博客&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://zhourudong.cn/2017/02/16/23-python装饰器/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《python装饰器》 — Cucy的博客&url=http://zhourudong.cn/2017/02/16/23-python装饰器/&via=http://zhourudong.cn" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://zhourudong.cn/2017/02/16/23-python装饰器/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/02/16/24-python正则re/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">python正则re</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/02/15/22-python环境/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">python环境</h4>
      </a>
    </div>
  
</nav>



    














</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        谢谢大爷~
        <i class="icon icon-quote-right"></i>
    </h3>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" src="/img/wechat.jpg" alt="打赏二维码">
        </div>
        
        <label class="reward-toggle">
            <input id="rewardToggle" type="checkbox" class="reward-toggle-check"
                data-wechat="/img/wechat.jpg" data-alipay="/img/alipay.jpg">
            <div class="reward-toggle-ctrol">
                <span class="reward-toggle-item wechat">微信</span>
                <span class="reward-toggle-label"></span>
                <span class="reward-toggle-item alipay">支付宝</span>
            </div>
        </label>
        
    </div>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>cucy &copy; 2016 - 2021</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://zhourudong.cn/2017/02/16/23-python装饰器/&title=《python装饰器》 — Cucy的博客&pic=http://zhourudong.cn/img/avatar.png" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://zhourudong.cn/2017/02/16/23-python装饰器/&title=《python装饰器》 — Cucy的博客&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://zhourudong.cn/2017/02/16/23-python装饰器/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《python装饰器》 — Cucy的博客&url=http://zhourudong.cn/2017/02/16/23-python装饰器/&via=http://zhourudong.cn" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://zhourudong.cn/2017/02/16/23-python装饰器/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=http://zhourudong.cn/2017/02/16/23-python装饰器/" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };


</script>

<script src="/js/main.min.js?v=1.6.13"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/js/search.min.js?v=1.6.13" async></script>






<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '死鬼去哪里了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!又好了!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
